import Vue from 'vue';
import { constantRoutes } from '@/routers'
import { getRouters } from '@/api/login'
// import { getRouters } from '@/api/demo'
import Layout from '@/layout/index'
import { getChildRouters } from '../../api/login'
// import ParentView from '@/components/ParentView';
// import InnerLink from '@/layout/components/InnerLink'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      console.log(state, routes,'state, routes');
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
        state.defaultRoutes = [...constantRoutes, ...routes]
    //   state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      // 顶部导航菜单默认添加统计报表栏指向首页
      // const index = [{
      //   path: 'index',
      //   meta: { title: '统计报表', icon: 'dashboard' }
      // }]
      // state.topbarRouters = routes.concat(index);

      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes;
    },
    clearPermission(state){
      state.routes = []
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes ({ commit }) {
      return new Promise(resolve => {
        // 向后端请求主账号路由数据
        getRouters().then(res => {
          let sidebarRoutes=[];
          let rewriteRoutes=[];
          if(res.result){
            console.log(res);
            // debugger
            const sdata = JSON.parse(JSON.stringify(res.result.firstMenuList))
            const rdata = JSON.parse(JSON.stringify(res.result.firstMenuList))
            sidebarRoutes = filterAsyncRouter(sdata)
            rewriteRoutes = filterAsyncRouter(rdata)
            console.log(rewriteRoutes,'rewriteRoutesrewriteRoutes');
            rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
            rewriteRoutes.map(item=>{
              Vue.set(item,'ismanageOffer',true);
              if(item.childMenuList){
                item.childMenuList.map(val=>{
                  Vue.set(val,'ismanageOffer',true);
                })
              }
            })
            console.log(rewriteRoutes,'rewriteRoutesrewriteRoutes');
            commit('SET_ROUTES', rewriteRoutes)
            commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            resolve(rewriteRoutes)
          }
          // console.log(rewriteRoutes,'rewriteRoutesrewriteRoutes');
          // commit('SET_ROUTES', rewriteRoutes)
          // commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
          // commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          // commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          // resolve(rewriteRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter (asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    // console.log(route,'333333');
    if (type && route.childMenuList&& route.type==1) {
      route.childMenuList = filterChildren(route.childMenuList)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.childMenuList != null && route.childMenuList && route.childMenuList.length&& route.type==1&&route.childMenuList[0].type==1) {
      // if(route.id==6){
      //   const index = route.childMenuList.findIndex((item)=>item.id=='6-3');
      //   if(index!=-1){
      //     route.childMenuList.splice(index,1);
      //   }
      // }
      route.childMenuList = filterAsyncRouter(route.childMenuList, route, type)
    } else {
      delete route['childMenuList']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren (childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
